Param($StartPath)
#Write-Output "Looking for movies with external subs in '$StartPath'..."

$all_start = Get-Date

$global:n_w_subs = 0
$global:n_wo_subs = 0

function MuxSubs([string] $WorkPath) {
    Write-Output "Looking for movies with external subs in '$WorkPath'..."
    $items = Get-ChildItem $WorkPath | where {! $_.PSIsContainer}
    ForEach ($item in $items) {
        if ($item -match "(.*)\.(avi|mkv|mp4)") {
            $movie_base = $matches[1]
            $movie_ext = $matches[2]
            $subs_regex = $movie_base + "\.(srt|idx|sub)"
            $subs = Get-ChildItem $WorkPath | where {
                (! $_.PSIsContainer) -and ($_ -match $subs_regex)
            }
            switch ($subs.Count) { 
                0   {
                    $global:n_wo_subs++
#                    Write-Host "    Movie '" -nonewline; Write-Host "$item" -f red -nonewline
#                    Write-Host "' have no external subs."
                } 
                default {
                    $global:n_w_subs++
#                    $movie_base = $matches[1]
#                    $item_path = Join-Path $PSScriptRoot $item
#                    $item_new_name = $movie_base + ".srt"
#                    Rename-Item -Path $item_path -NewName $item_new_name
                    Write-Host "    Movie '" -nonewline; Write-Host "$item" -f green -nonewline
                    Write-Host "' have one or more external subs! Trying to merge them:"
                    $MkvOut = Join-Path $WorkPath ($movie_base + "_SUBMUX.mkv")
                    $MkvIn = Join-Path $WorkPath ($movie_base + "." + $movie_ext)
#                    $MkvSubs = $subs | foreach {Join-Path $WorkPath $_.FullName}
                    $MkvSubs = $subs | foreach {$_.FullName}
                    mkvmerge.exe -o $MkvOut $MkvIn $MkvSubs
                    if ($lastexitcode -eq 0) {
                        Write-Host "        Muxing successful, removing input files."
                        Remove-Item $MkvIn
                        $subs | foreach {Remove-Item $_.FullName}
                    }
                    else {
                        Write-Host "        Hmm, mkvmerge failed somehow!"
                    }
                } 
            }
        }
    }
    $subdirs = Get-ChildItem $WorkPath | where {$_.PSIsContainer}
    ForEach ($subdir in $subdirs) {
        MuxSubs (Join-Path $WorkPath $subdir)
    }
}

MuxSubs $StartPath

function GetNow() {
    return Get-Date -format "yyyy-MM-dd HH:mm:ss"
}

$all_end = Get-Date
$total_time = New-Timespan $all_start $all_end
$now = GetNow
Write-Output "`n"
Write-Output "Finished at $now. Processing took $total_time."
Write-Output "Found $global:n_wo_subs movies without external subs."
Write-Output "Found $global:n_w_subs movies with external subs."
